package com.sitc.street_lab_2013.entityLogic;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sitc.street_lab_2013.entities.Answer;
import com.sitc.street_lab_2013.helpers.DBHelper;

public class AnswerLogic {

	private SQLiteDatabase database;
	private DBHelper dbHelper;
	private String [] columns = { 
			DBHelper.ANS_ID,
			DBHelper.ANS_QID,
			DBHelper.ANS_TEXT,
			DBHelper.ANS_MOREINFO,
			DBHelper.ANS_ISCORRECT };
	
	public AnswerLogic(Context c){
		dbHelper = new DBHelper(c);
	}
	
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public boolean createAnswer(Answer ans)
	{
		try {
			open();
			
			ContentValues values = new ContentValues();
			values.put(DBHelper.ANS_QID, ans.getAnsQuestionId());
			values.put(DBHelper.ANS_TEXT, ans.getAnsText());
			values.put(DBHelper.ANS_MOREINFO, ans.getAnsMoreInfo());
			values.put(DBHelper.ANS_ISCORRECT, ans.isAnsIsCorrect());
			
			long insertId = database.insert(DBHelper.TABLE_ANSWERS, null, values);
			
			if (insertId != -1)
				return true;
		}
		catch(Exception e){
			Log.e("ERROR CREATE ANSWER, ", e.getCause().getMessage());
		} finally {
			close();
		}
		
		return false;
	}
	

	public int deleteAllAnswers() {
		try {
			open();
			return database.delete(DBHelper.TABLE_ANSWERS, null, null);

		} catch (Exception e) {
			Log.e("ERROR DELETE ALL ANSWERS", e.getCause().getMessage());
		} finally {
			close();
		}

		return 0;
	}
			
	
	public ArrayList<Answer> getAnswersByLocation(int locId)
	{
		ArrayList<Answer> answers = new ArrayList<Answer>();
		Cursor c = null;
		
		try{
			open();
			
			c = database.rawQuery(
				"SELECT * " 
				+ " FROM " + DBHelper.TABLE_ANSWERS 
				+ " WHERE " + DBHelper.ANS_QID + " = " + locId + ";", null);
			
			c.moveToFirst();
			
			while(!c.isAfterLast()){
				Answer ans = cursorToAnswer(c);
				answers.add(ans);
				c.moveToNext();
			}
		}
		catch(Exception e){
			Log.e("ERROR GET ANSWERS ", e.getCause().getMessage());
		} finally {
			close();
		}
		
		return answers;
	}

	
	public Answer cursorToAnswer(Cursor c){		
		Answer a = new Answer(
					c.getInt(0), 
					c.getInt(1), 
					c.getString(2), 
					c.getInt(3), 
					c.getString(4));
		
		return a;
	}
}
